/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.wicket.panel.grid.column;

import java.util.ArrayList;
import java.util.List;

import com.eelpo.cmmp.core.wicket.panel.grid.column.ColumnLocation.Unit;

import org.apache.wicket.Component;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.Response;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;

/**
 * 表头加样式
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class ColumnHeaderContainer<T> extends WebMarkupContainer {

	private static final long serialVersionUID = 9117786377011795137L;
	private final List<Component> components = new ArrayList<Component>();
	private final List<IColumnHeader<T>> columns = new ArrayList<IColumnHeader<T>>();

	public ColumnHeaderContainer(String id) {
		super(id);
		setRenderBodyOnly(true);
	}

	public void addColumn(IColumnHeader<T> column, Component component) {
		columns.add(column);
		components.add(component);
	}

	@Override
	protected void onRender(final MarkupStream markupStream) {

		int markupStart = markupStream.getCurrentIndex();
		Response response = RequestCycle.get().getResponse();

		boolean rendered = false;
		for (int i = 0; i < columns.size(); ++i) {
			IColumnHeader<T> column = columns.get(i);
			Component component = components.get(i);
			response.write("<th style=\"" + renderColumnStyle(column) + "\">");

			if (component != null) {
				markupStream.setCurrentIndex(markupStart);
				component.render(markupStream);
				rendered = true;
			}
			response.write("</th>\n");
		}

		if (!rendered) {
			markupStream.skipComponent();
		}
	}

	/**
	 * Renders content of the style attribute for the given column.
	 * 
	 * @param column
	 *            The column to render the style attribute from
	 * @return The style as a string
	 */
	private String renderColumnStyle(IColumnHeader<T> column) {
		return "width:" + renderColumnWidth(column);
	}

	/**
	 * Renders width of given column as string.
	 * 
	 * @param column
	 *            The column to render as a string
	 * @return The column as a string
	 */
	private String renderColumnWidth(IColumnHeader<T> column) {
		ColumnLocation location = column.getLocation();
		return String.valueOf(location.getSize()).concat(renderUnit(location.getUnit()));
	}

	/**
	 * Renders given unit as string.
	 * 
	 * @param unit
	 *            The unit to render to a string
	 * @return The unit as a string
	 */
	private String renderUnit(Unit unit) {
		if (unit == Unit.EM) {
			return "em";
		} else if (unit == Unit.PX) {
			return "px";
		} else if (unit == Unit.PERCENT) {
			return "%";
		} else {
			throw new IllegalStateException("Wrong column unit for column aligned left or right.");
		}
	}

}
